import { Component, OnInit, ViewChild } from '@angular/core'
import { AcquirerNewBaseClass } from '../baseClass'
import { FormBuilder } from '@angular/forms'
import { AcquirerStoreService } from '../acquirer-store.service'

@Component({
  selector: 'app-acquirer-new-card-func',
  templateUrl: './card-func.component.html',
})
export class AcquirerNewCardFuncComponent extends AcquirerNewBaseClass implements OnInit {
  tradeTypes: string[] = []

  tradeTypeOptions = [
    {
      label: '下单',
      value: 'todo0',
      checked: true,
    },
    {
      label: '预下单',
      value: 'todo1',
      checked: false,
    },
    {
      label: '固定码',
      value: 'todo2',
      checked: false,
    },
    {
      label: '退款',
      value: 'todo3',
      checked: false,
    }
  ]

  constructor(
    public fb: FormBuilder,
    public acquirerStore: AcquirerStoreService,
  ) {
    super(fb, acquirerStore)
  }

  ngOnInit() {
    this.initValidateForm()
  }

  initValidateForm(): void {
    const { isRefundAsync, tradeTypes } = this.acquirer.institution.card
    this.renderTradeTypeOptions(tradeTypes)

    this.validateForm = this.fb.group({
      isRefundAsync: [`${isRefundAsync}`, []],
      tradeTypes: [this.tradeTypeOptions, []],
    })
  }

  checkValid() {
    this.pushDataToStore()
    return true
  }

  pushDataToStore(): void {
    const tmp = this.validateForm.value
    tmp.isRefundAsync = tmp.isRefundAsync === 'true' ? true : false
    tmp.tradeTypes = this.analyseTradeTypeOptions(this.tradeTypeOptions)
    this.acquirer.institution.card = tmp
    this.acquirerStore.updateValue(this.acquirer)
  }

  renderTradeTypeOptions(tradeType: string[]) {
    this.tradeTypeOptions.forEach(option => {
      if (tradeType.includes(option.value)) {
        option.checked = true
      }
    })
  }

  analyseTradeTypeOptions(tradeTypeOptions: any[]): string[] {
    return tradeTypeOptions
      .filter(option => option.checked)
      .map(option => option.value)
  }

}
